﻿using DevelopAssistant.Service.TemplatingEngine;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DevelopAssistant.Service
{
    internal class Creater
    {
        internal static string CreateCode(TextTemplatingEngine host, string csType, string templateFile, string savePath,
         string outType, out string message)
        {
            host.TemplateFile = templateFile;
            Microsoft.VisualStudio.TextTemplating.Engine engine = new Microsoft.VisualStudio.TextTemplating.Engine();

            string input = "";
            string output = "";

            input = System.IO.File.ReadAllText(host.TemplateFile);
            output = engine.ProcessTemplate(input, host);
            message = string.Empty;

            if (outType == "File")
            {
                try
                {
                    string outputFile = savePath + host.ClassName + host.FileExtension;
                    if (System.IO.Directory.Exists(savePath))
                    {
                        System.IO.File.WriteAllText(outputFile, output);
                    }
                    else
                    {
                        System.IO.Directory.CreateDirectory(savePath);
                        System.IO.File.WriteAllText(outputFile, output);
                    }
                }
                catch (Exception error)
                {
                    message += error.ToString() + "\r\n";
                }
            }

            message += host.ClassName + " " + csType + " 代码生成成功" + "\r\n";

            foreach (CompilerError error in host.Errors)
            {
                message += error.ToString() + "\r\n";
            }

            return output;
        }
    }
}
